<template>
  <el-dialog
    title="备用金支付"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="单据编号" prop="number">
            <el-input v-model="form.number" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请支付" prop="applyPayment">
            <el-input v-model="form.applyPayment" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批复金额" prop="approvedAmount">
            <el-input v-model="form.approvedAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务内容摘要" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>

      </el-row>

      <div class="btns" style="padding-bottom: 10px;">
        <el-button type="primary" @click="showAddDetailModal = true;">新增行</el-button>
        <el-button type="primary" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:sequence="{row}">
          <el-input v-model="row.sequence" />
        </template>
        <template v-slot:fundUse="{row}">
          <el-select v-model="row.fundUse" :disabled="disableForm" style="width: 100%;" placeholder="请选择资金用途">
            <el-option v-for="item in paymentFundUse" :key="item.name" :label="item.name" :value="item.value" />
          </el-select>
        </template>
        <template v-slot:accountSubjects="{row}">
          <el-select v-model="row.accountSubjects" :disabled="disableForm" style="width: 100%;" placeholder="请选择会计科目">
            <el-option v-for="item in paymentAccountSubjects" :key="item.name" :label="item.name" :value="item.value" />
          </el-select>
        </template>
        <template v-slot:reimbursePersonal="{row}">
          <el-input v-model="row.reimbursePersonal" />
        </template>
        <template v-slot:reimburseAmount="{row}">
          <el-input v-model="row.reimburseAmount" />
        </template>
        <template v-slot:invoiceAmount="{row}">
          <el-input v-model="row.invoiceAmount" />
        </template>
        <template v-slot:applyPayment="{row}">
          <el-input v-model="row.applyPayment" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:lstAttachment="{row}">
          <a class="com-link" @click="uploaderFielRow(row)">文件数（{{ row.lstAttachment.length }}）</a>
        </template>
      </com-table>
      <!-- <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button> -->
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <el-dialog
      title="新增备用金支付"
      :visible.sync="showAddDetailModal"
      width="700px"
      center
      append-to-body
    >
      <el-form ref="detailForm" :rules="detailRules" style="padding-top: 10px;" :model="detailDataItem" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="sequence">
              <el-input v-model="detailDataItem.sequence" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资金用途" prop="fundUse">
              <el-select v-model="detailDataItem.fundUse" :disabled="disableForm" style="width: 100%;" placeholder="请选择资金用途">
                <el-option v-for="item in paymentFundUse" :key="item.name" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会计科目" prop="accountSubjects">
              <el-select v-model="detailDataItem.accountSubjects" :disabled="disableForm" style="width: 100%;" placeholder="请选择会计科目">
                <el-option v-for="item in paymentAccountSubjects" :key="item.name" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报销人" prop="reimbursePersonal">
              <el-input v-model="detailDataItem.reimbursePersonal" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报销金额" prop="reimburseAmount">
              <el-input v-model="detailDataItem.reimburseAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input v-model="detailDataItem.invoiceAmount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请支付" prop="applyPayment">
              <el-input v-model="detailDataItem.applyPayment" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="detailDataItem.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddDetail">取 消</el-button>
        <el-button type="success" icon="el-icon-plus" @click="addDetail">确 定</el-button>
      </span>
    </el-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addReservePaymentInfo, updateReservePaymentInfo, getReservePaymentInfoDetail } from '@/api/moneyManage'
import { getAreaList } from '@/api/common'
import { paymentFundUse, paymentAccountSubjects, workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddReservePaymentInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      targetList: [],
      paymentFundUse,
      paymentAccountSubjects,
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        // number: '',
        projectName: '',
        applyPayment: '',
        approvedAmount: '',
        description: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {
      },
      columns: [
        {
          label: '序号',
          slot: 'sequence'
        },
        {
          label: '资金用途',
          slot: 'fundUse'
        },
        {
          label: '会计科目',
          slot: 'accountSubjects'
        },
        {
          label: '报销人',
          slot: 'reimbursePersonal'
        },
        {
          label: '报销金额',
          slot: 'reimburseAmount'
        },
        {
          label: '发票金额',
          slot: 'invoiceAmount'
        },
        {
          label: '申请支付',
          slot: 'applyPayment'
        },
        {
          label: '备注',
          slot: 'remark'
        },
        {
          label: '附件',
          slot: 'lstAttachment'
        }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'change' }
        ]
      },
      detailRules: {
        sequence: [
          { required: true, message: '请输入序号', trigger: 'change' }
        ],
        reimbursePersonal: [
          { required: true, message: '请输入报销人', trigger: 'change' }
        ],
        reimburseAmount: [
          { required: true, message: '请输入报销金额', trigger: 'change' }
        ],
        invoiceAmount: [
          { required: true, message: '请输入发票金额', trigger: 'change' }
        ],
        applyPayment: [
          { required: true, message: '请输入申请支付', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
        this.fileList = []
      }
    }
  },
  watch: {
    fileList(val) {
      if (this.uploadRow) {
        this.uploadRow.lstAttachment = val
      }
    },
    showFileModal(val) {
      if (!val) {
        this.uploadRow = null
      }
    },
    showModal(val) {
      if (val) {
        if (this.optType === 'edit') {
          this.getDocDetail(this.data.id)
        }
      } else {
        this.fileList = []
        this.detailDataList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    uploaderFielRow(row) {
      this.uploadRow = row
      this.fileList = row.lstAttachment
      this.showFileModal = true
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push({
            ...item,
            lstAttachment: []
          })
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getReservePaymentInfoDetail({ reservePaymentInfoId: id }).then(res => {
        const { lstReservePaymentDetail, reservePaymentInfo } = res.data || {}
        if (lstReservePaymentDetail && lstReservePaymentDetail.length > 0) {
          this.detailDataList = lstReservePaymentDetail.map(item => {
            return {
              ...item.reservePaymentDetail,
              lstAttachment: item.lstAttachment
            }
          })
        }
        Object.keys(this.form).forEach(key => {
          this.form[key] = reservePaymentInfo[key]
        })
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            reservePaymentInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstReservePaymentDetail: this.detailDataList.map(item => {
              const { lstAttachment, ...Obj } = item
              return {
                reservePaymentDetail: {
                  ...Obj
                },
                lstAttachment
              }
            })

          }
          const fn = this.optType === 'add' ? addReservePaymentInfo : updateReservePaymentInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
